;
(function () {
  var ACCOUNTID = hlUrlUtil.GetQueryString('id'); //账单id
  var CONTRACTID = hlUrlUtil.GetQueryString('aid'); //合同id
  var PAGE = hlUrlUtil.GetQueryString('page'); //合同id
  var permissions = window.localStorage.getItem('permissions') //page

  Array.prototype.removeRepeatBuildingAndFLoor = function () {
    var res = [this[0]];
    for (var i = 1; i < this.length; i++) {
      var repeat = false;
      for (var j = 0; j < res.length; j++) {
        if (this[i].buildingName == res[j].buildingName && this[i].floorNum == res[j].floorNum) {
          repeat = true;
        }
      }
      if (!repeat) {
        res.push(this[i]);
      }
    }
    return res;
  };

  new Vue({
    el: '#bill-detail',
    data: {
      idA: {
        ida: ACCOUNTID,
        idb: CONTRACTID
      },
      contractData: {
        ot: [],
        st: []
      },
      billData: {
        expenses: [],
        transactions: [],
        invoiceInfos: [],
        carryOverInfos: []
      },
      expenses_copy: [], //保存的上一次费项
      editFlag: true,
      temporary: 0,
      permissions: JSON.parse(permissions),
      costItem: [],
      fPData: [],
      fpPut: [],
      fpFlag: false,
      closeFlag: false,
      memo: {
        content: '',
        flag: false
      },
      proid: '',
      fPIS: 0,
      NIS: 0,
      plFp: 0,
      Fp: [],
      jlFp: [],
      page: PAGE,
      st: [], // 车位
      wp: [], // 工位
      stTotalNum: 0, // 车位总数
      wpTotalNum: 0, // 工位总数
      totalArea: 0, // 单元总面积
      building: [], // 楼宇信息
      projectName: null, // 项目名
      unitOpenFlag: false,
      wpOpenFlag: false,
      stOpenFlag: false,
      CZOpenFlag: false,
      printflag: true,
      isEditCountMes: false,
      receiptDeadlineDate: null,
      aa: null,
      logData: [],
      IsCompareRentAmtFlag: false,
      isPaymantflag: false,

      isChangeJMFlag: false,
      isChangeLSFlag: false,
      isChangeNewFlag: hlUrlUtil.GetQueryString('type') == 'new' ? true : false,

      billBpmConfigArr: [],
      zlfCompanySpecial:''
    },
    filters: {
      timestamp: function (time) {
        return hlDateUtil.formatUTCDate(time, 'yyyy-MM-dd')
      },
      billState: function (state) {
        if (!state) return '';
        return hlCodeConvert.billPaymentState(state)
      },
      toFixed2: function (n) {
        return Number(n).toFixed(2)
      },
      billPayWay: function (state) {
        return hlCodeConvert.billPayWay(state)
      },
      //千分位
      formatNum: function (n) {
        return hlNumberUtil.formatNum(n)
      },
      absNum: function (n) {
        return Math.abs(n)
      }
    },
    computed: {
      temporarys: function () {
        let res = 0;
        for (var i = 0; i < this.billData.expenses.length; i++) {
          if (this.billData.expenses[i].expenseType === 'T') {
            res++
          }
        }
        return res
      },
      fPDataNum: function () {
        var result = 0;
        for (var i = 0; i < this.fPData.length; i++) {
          if (this.fPData[i].expenseType === 'T') {
            result++
          }
        }
        return result
      },
      //应收本金
      totalYS: function () {
        var result = 0; //总和
        var IS = 0; //已收款
        this.billData.expenses.map(function (item) {
          if (Number(item.amountReceived) > 0) {
            result += Number(item.amountReceived)
          }
        })
        return result
      },
      //已收本金
      totalIS: function () {
        var result = 0; //总和
        this.billData.expenses.map(function (item) {
          result += Number(item.amountPayed);
        })
        return result
      },
      //减免本金
      totalJM: function () {
        var result = 0; //总和
        this.billData.expenses.map(function (item) {
          result += Number(item.amountDerate);
        })
        return result
      },
      //结转抵扣 (应收)
      carryOverTotalAmount: function () {
        var result = 0; //总和
        this.billData.expenses.map(function (item) {
          if (item.carryOverTotalAmount > 0 && item.amountReceived > 0) {
            result += Number(item.carryOverTotalAmount);
          }
        })
        return result
      },
      //本次应收本金
      totalBCYS: function () {
        var result = 0; //总和
        result = this.totalYS - this.totalIS - this.totalJM - this.carryOverTotalAmount;
        return result
      },
      //应收滞纳金
      totalYSznj: function () {
        var result = 0; //总和
        var IS = 0; //已收款
        this.billData.expenses.map(function (item) {
          result += Number(item.lateFeeReceived)
        })
        return result
      },
      //已收滞纳金
      totalISznj: function () {
        var result = 0; //总和
        this.billData.expenses.map(function (item) {
          result += Number(item.lateFeePayed);
        })
        return result
      },
      //减免滞纳金
      totalJMznj: function () {
        var result = 0; //总和
        this.billData.expenses.map(function (item) {
          result += Number(item.lateFeeDerate);
        })
        return result
      },
      //本次应收滞纳金
      totalBCYSznj: function () {
        var result = 0; //总和
        // result = this.totalYSznj - this.totalISznj - this.totalJMznj;
        this.billData.expenses.map(function (item) {
          result += Number(item.lateFeeTPay)
        })
        return result
      },
      //本次应退
      totalYT: function () {
        var result = 0; //总和
        this.billData.expenses.map(function (item) {
          result += Math.abs(Number(item.amountRefund))
        })
        return result
      },
      //已退本金
      totalIT: function () {
        var result = 0; //总和
        this.billData.expenses.map(function (item) {
          result += Math.abs(Number(item.refundPayed))
        })
        return result
      },
      //结转抵扣 (应退)
      carryOverTotalAmountYt: function () {
        var result = 0; //总和
        this.billData.expenses.map(function (item) {
          if (item.carryOverTotalAmount > 0 && item.amountRefund > 0) {
            result += Number(item.carryOverTotalAmount);
          }
        })
        return result
      },
      //本次应退
      totalBCYT: function () {
        var result = 0; //总和
        result = this.totalYT - this.totalIT - this.carryOverTotalAmountYt
        return result
      },
      //本次应收合计
      totalYSHJ: function () {
        var result = 0; //总和
        result = this.totalBCYS + this.totalBCYSznj - this.totalBCYT;
        if (this.totalNum == 1) {
          this.txs[0]['amountTPay'] = Number(result).toFixed(2);
        }
        this.totalNum++;
        return Number(result).toFixed(2)
      },

      cumulation: function () {
        var result = 0;
        this.txs.map(function (item) {
          result += Number(hlNumberUtil.formatThousandsNum(item.amountTPay))
        })
        return Number(result).toFixed(2);
      }
    },
    methods: {
      bill_bpm_config() {
        hlhttp.get({
          url: 'configure/bill_bpm_config/dict',
          success: res => {
            if (res.open_flag == 'N') return
            res.dict_property = JSON.parse(res.dict_property)
            this.billBpmConfigArr = res.dict_property.billBpmValue
          }
        })
      },
      //去账单详情
      goTobill(id) {
        hlUrlUtil.goTo('billDetail', {
          id: id,
          aid: CONTRACTID,
          ddtab: true
        }, true)
      },
      //初始化
      resetInit: function () {
        var self = this;
        hllayer.confirm1('账单撤回后<br/>所有收款、结转记录将清空，确认继续操作', () => {
          hlhttp.put({
            url: 'bill/init',
            data: {
              bill_id: ACCOUNTID
            },
            success: function () {
              hl.toast('账单撤回成功')
              if (!self.billData.intentId) {
                self.getContractUnitsData()
                self.getContractData()
              }
              self.getBillData()
              self.getlogData()
            }
          })
        })
      },
      // 获取合同单元信息
      getContractUnitsData: function () {
        var self = this;
        hlhttp.get({
          url: 'contract/units',
          data: {
            id: CONTRACTID
          },
          success: function (data) {
            // 单元
            var buildingData = self.dealWithUnitData(data)
            self.totalArea = buildingData.totalArea
            self.building = buildingData.building
            // 车位
            self.st = [];
            self.wp = [];
            var stTotalNum = 0;
            var wpTotalNum = 0;
            data.map(function (item) {
              if (item.positions && item.unitType === 'ST') {
                stTotalNum = stTotalNum + item.positions.length;
                item['num'] = item.positions.length;
                self.st.push(item)
              }
              if (item.positions && item.unitType === 'WP') {
                wpTotalNum = wpTotalNum + item.positions.length;
                item['num'] = item.positions.length;
                self.wp.push(item)
              }
            })
            self.stTotalNum = stTotalNum;
            self.wpTotalNum = wpTotalNum;
          }
        })
      },
      // 单元数据去重整合处理
      dealWithUnitData: function (unitsData) {
        // 去除含有工位车位的单元
        var units = [];
        unitsData.map(function (_item) {
          if (_item.positions.length === 0) {
            units.push(_item)
          }
        })
        if (units.length === 0) {
          return {
            building: [],
            totalArea: 0
          }
        }
        // 合并单元项
        var unit = [];
        var totalArea = 0;
        for (var i = 0; i < units.length; i++) {
          unit.push({
            buildingName: units[i].buildingName,
            floorNum: units[i].floorNum,
            floorName: units[i].floorName,
            unit: []
          })
        }
        var unitArr = unit.removeRepeatBuildingAndFLoor()
        for (var z = 0; z < unitArr.length; z++) {
          for (var m = 0; m < units.length; m++) {
            if (units[m].buildingName == unitArr[z].buildingName && units[m].floorNum == unitArr[z].floorNum) {
              unitArr[z].unit.push(units[m].unitName + '(' + hlNumberUtil.formatNum(units[m].unitAcreage) + 'm²)')
              totalArea = totalArea + Number(units[m].unitAcreage)
            }
          }
        }
        // 合并楼层项
        var building = [];
        for (var j = 0; j < unitArr.length; j++) {
          building.push({
            buildingName: unitArr[j].buildingName,
            floor: []
          })
        }
        var buildingArr = hlArrayUtil.removeRepeat(building, 'buildingName')
        for (var k = 0; k < buildingArr.length; k++) {
          for (var n = 0; n < unitArr.length; n++) {
            if (unitArr[n].buildingName == buildingArr[k].buildingName) {
              buildingArr[k].floor.push({
                'floorNum': unitArr[n].floorNum,
                'floorName': unitArr[n].floorName,
                'unit': unitArr[n].unit
              })
            }
          }
        }
        return {
          building: buildingArr,
          totalArea: totalArea
        }
      },
      // 查看出租资源详情信息
      checkDetailMes: function (type) {
        var self = this;
        if (type === 'unit') {
          if (self.unitOpenFlag === true) {
            self.unitOpenFlag = false
            return false
          }
          if (self.unitOpenFlag === false) {
            self.unitOpenFlag = true
            return false
          }
        }
        if (type === 'wp') {
          if (self.wpOpenFlag === true) {
            self.wpOpenFlag = false;
            return false;
          }
          if (self.wpOpenFlag === false) {
            self.wpOpenFlag = true
            return false;
          }
        }
        if (type === 'st') {
          if (self.stOpenFlag === true) {
            self.stOpenFlag = false
            return false;
          }
          if (self.stOpenFlag === false) {
            self.stOpenFlag = true
            return false;
          }
        }
      },
      //获取合同信息
      getContractData: function () {
        var _this = this;
        contract.formatUnitData(CONTRACTID, function (data) {
          _this.contractData = data
        })
      },
      //跳转营业额详情
      gotoCommisson() {
        hlUrlUtil.goTo('commissionDetail', {
          'id': ACCOUNTID,
          ddtab: true
        })
      },
      //获取意向详情
      getYxInfo(id) {
        var self = this;
        hlhttp.get({
          url: 'contract/intent',
          data: {
            id: id
          },
          success: (data) => {
            data.projectInfo.units.map(item => {
              item.positions = [];
              item.floorName = item.floorNum
            })
            this.contractData.zlfCompany = data.zlfInfo.zlfName
            this.contractData.projectName = data.projectInfo.projectName
            var buildingData = this.dealWithUnitData(data.projectInfo.units)
            this.totalArea = buildingData.totalArea
            this.building = buildingData.building;
            this.st = [];
            this.wp = [];
            var stTotalNum = 0;
            var wpTotalNum = 0;
            //车位
            let newStArr = hlArrayUtil.removeRepeat(data.projectInfo.stops, 'unitId'),
              newStIds = [];
            newStArr.map(item => {
              item.floor = item.floorNum;
              item.floorName = item.floorNum
              item.positions = []
            })
            data.projectInfo.stops.map(item => {
              newStIds.push(item.stopId)
              newStArr.map(item1 => {
                if (item.unitId == item1.unitId) {
                  stTotalNum++
                  item1.positions.push({
                    positionName: item.stopName,
                    positionId: item.stopId
                  })
                }
              })
            })
            self.st = newStArr;
            let newWpArr = hlArrayUtil.removeRepeat(data.projectInfo.wps, 'unitId'),
              newWpIds = [];
            newWpArr.map(item => {
              item.floor = item.floorNum
              item.positions = []
            })
            data.projectInfo.wps.map(item => {
              newWpIds.push(item.wpId)
              newWpArr.map(item1 => {
                if (item.unitId == item1.unitId) {
                  wpTotalNum++
                  item1.positions.push({
                    positionName: item.wpName,
                    positionId: item.wpId
                  })
                }
              })
            })
            this.wp = newWpArr
            self.stTotalNum = stTotalNum;
            self.wpTotalNum = wpTotalNum;
          }
        })
      },
      //获取账单信息
      getBillData: function () {
        var _this = this;
        hlhttp.get({
          url: 'bill,expenses,transactions',
          data: {
            bill_id: ACCOUNTID
          },
          success: function (data) {
            _this.zlfCompanySpecial = data.zlfCompany
            if (data.intentId) _this.getYxInfo(data.intentId)
            CONTRACTID = data.contractId
            _this.idA.idb = data.contractId
            if (CONTRACTID) {
              _this.getContractData()
            }
            data.expenses.map(item => {
              item.derate_expense_update_flag = item.derateExpenseUpdateFlag && item.derateExpenseUpdateFlag == 'Y' ? 'Y' : 'N';
              item.derate_late_fee_update_flag = item.derateLateFeeUpdateFlag && item.derateLateFeeUpdateFlag == 'Y' ? 'Y' : 'N';
              item.late_fee_received_update_flag = item.lateFeeReceivedUpdateFlag && item.lateFeeReceivedUpdateFlag == 'Y' ? 'Y' : 'N';
              item.expense_name_update_flag = item.nameUpdateFlag && item.nameUpdateFlag == 'Y' ? 'Y' : 'N';
              item.expense_amount_update_flag = item.amountReceiveUpdateFlag && item.amountReceiveUpdateFlag == 'Y' ? 'Y' : 'N';
              item.expense_memo_update_flag = item.memoUpdateFlag && item.memoUpdateFlag == 'Y' ? 'Y' : 'N';
              item.lateFeeTPayUpdateFlag = item.lateFeeTPayUpdateFlag && item.lateFeeTPayUpdateFlag == 'Y' ? 'Y' : 'N';
            })
            _this.expenses_copy = JSON.parse(JSON.stringify(data.expenses || []))
            _this.billData = data;
            _this.proid = data.projectId;

            for (var i = 0; i < _this.billData.transactions.length; i++) {
              _this.billData.transactions[i].flag = false;
              _this.Fp.push({
                index: '',
                id: '',
                flag: ''
              })
            }
            loginPrem.loginList()


            console.log(_this.permissions);

            if (_this.permissions.indexOf('c96') > -1) {
              if (hlUrlUtil.GetQueryString('page') == 'businessList') {
                if (_this.billData.billState == 'WTJ' && _this.billData.paymentState == 'WP') {
                  _this.printflag = false
                }
                if (_this.billData.billState == 'WSK' && _this.billData.paymentState == 'WP') {
                  _this.printflag = false
                }
                if (_this.billData.billState == 'WTJ' && _this.billData.paymentState == 'PPE') {
                  _this.printflag = false
                }
                if (_this.billData.billState == 'WSK' && _this.billData.paymentState == 'PPE') {
                  _this.printflag = false
                }
              }
            }

            if (_this.permissions.indexOf('c95') > -1) {
              if (hlUrlUtil.GetQueryString('page') == 'billList') {
                if (_this.billData.billState == 'WTJ' && _this.billData.paymentState == 'WP') {
                  _this.printflag = false
                }
                if (_this.billData.billState == 'WSK' && _this.billData.paymentState == 'WP') {
                  _this.printflag = false
                }
                if (_this.billData.billState == 'WTJ' && _this.billData.paymentState == 'PPE') {
                  _this.printflag = false
                }
                if (_this.billData.billState == 'WSK' && _this.billData.paymentState == 'PPE') {
                  _this.printflag = false
                }
              }
            }

            _this.receiptDeadlineDate = hlDateUtil.formatUTCDate(data.deadlineDate, 'yyyy-MM-dd')
          }
        })
      },
      //获取日志详情
      getlogData() {
        var that = this
        hlhttp.get({
          url: 'bill/logs',
          data: {
            bill_id: ACCOUNTID
          },
          success: function (data) {
            that.logData = data.groupLogs
            that.logData.forEach(item => {
              if (item.operationName == '编辑账单费项') {
                item.logRecords.forEach(item1 => {
                  item1.list = []
                  for (var i = 0; i < item1.rowData.length; i += 3) {
                    item1.list.push(item1.rowData.slice(i, i + 3));
                  }
                })
              }
            })
          }
        })
      },
      //是否改变
      changeBill(i, type) {
        if (this.billData.expenses[i][type] == 'N') {
          this.billData.expenses[i][type] = 'Y'
        }
      },
      //编辑保存
      editSave: function (flag) {
        this.editFlag = flag;
        if (flag) {
          let expense_info = [];
          for (var i = 0; i < this.billData.expenses.length; i++) {
            item = this.billData.expenses[i];
            if (item.paymentState !== 'APE' && !item.styleFlag) {
              expense_info.push({
                expense_id: item.id,
                derate_expense: item.amountDerate,
                derate_late_fee: item.lateFeeDerate,
                // late_fee_received: item.lateFeeReceived,
                late_fee_tpay: item.lateFeeTPay,
                derate_expense_update_flag: item.derate_expense_update_flag == 'Y' ? 'Y' : 'N',
                derate_late_fee_update_flag: item.derate_late_fee_update_flag == 'Y' ? 'Y' : 'N',
                // late_fee_received_update_flag: item.late_fee_received_update_flag == 'Y' ? 'Y' : 'N'
                late_fee_tpay_update_flag: item.lateFeeTPayUpdateFlag == 'Y' ? 'Y' : 'N'
              })
            }
          }

          hlhttp.put({
            baseUrl: _url2,
            url: 'v2/bill',
            data: {
              bill_id: ACCOUNTID, //账单ID
              is_submit: 'N',
              expense_info: JSON.stringify(expense_info)
            },
            success: () => {
              hl.toast('账单编辑成功')
              this.isChangeJMFun()
              this.getBillData()
              this.getlogData()
              this.closeFlag = false;
            }
          })
        }
      },
      //  // 结算金额表格是否修改过
      isChangeJMFun() {
        let flag = false //金额减免标识
        this.expenses_copy.map((item, index) => {
          if (item.amountDerate != this.billData.expenses[index].amountDerate || item.lateFeeDerate != this.billData.expenses[index].lateFeeDerate) {
            flag = true
          }
        })
        this.isChangeJMFlag = flag
      },
      //计算减免本金
      computedJmBJ: function (jm, ys, is, i, carryOverTotalAmount) {
        if (jm > (ys - is - carryOverTotalAmount)) {
          this.billData.expenses[i].amountDerate = ys - is - carryOverTotalAmount;
          hl.toast('减免金额不能大于应收金额')
        }
        if (jm === 0) return;
        if (!Number(jm)) {
          this.billData.expenses[i].amountDerate = 0;
          hl.toast('减免金额不是数字')
        }
      },
      //计算减免滞纳金
      ifZnjNum: function (v, i) {
        if (v === 0) return;
        if (!Number(v)) {
          this.billData.expenses[i].lateFeeReceived = 0;
          hl.toast('应收滞纳金不是数字')
        }
        var total = Number(this.billData.expenses[i].lateFeePayed) +
          Number(this.billData.expenses[i].lateFeeDerate);
        if (this.billData.expenses[i].lateFeeReceived < total) {
          this.billData.expenses[i].lateFeeReceived = total;
          hl.toast('应收滞纳金不能小于已收滞纳金加减免滞纳金之和')
        }
      },
      computedJmZNJ: function (jm, ys, is, i) {

      },
      // 录入滞纳金、应收滞纳金
      computedZNJ(val, index, str) {
        if (val < 0) {
          if (str == 'lateFeeTPay') {
            hl.toast('滞纳金必须大于0')
            this.billData.expenses[index].lateFeeTPay = 0
          } else {
            hl.toast('减免滞纳金必须大于0')
            this.billData.expenses[index].lateFeeDerate = 0
          }
        }
      },

      //添加临时费项
      addItemCost: function () {
        this.costItem.push({
          name: '',
          memo: '',
          amountTPay: '',
          paymentState: 'WP'
        })
        this.temporary++;
      },
      //删除临时费项
      delCostItem: function (i) {
        this.costItem.splice(i, 1);
        this.temporary--;
      },
      delIdCostItem: function (id) {
        var _this = this;
        hllayer.confirm('确认删除此条费项？', function () {
          hlhttp.delete({
            url: 'bill/expense?id=' + id,
            success: function () {
              hl.toast('删除临时费项成功')
              _this.getBillData()
              _this.getlogData()
              $('.js-cancel-btn,.js-confirm-btn,.sh-2').addClass('hide')
              $('.js-amend,.sh-1').removeClass('hide')
            }
          })
        }, function () {
          $('.hllayer-view,.hllayer-mask').remove()
          $('.js-cancel-btn,.js-confirm-btn,.sh-2').addClass('hide')
          $('.js-amend,.sh-1').removeClass('hide')
        })
      },
      //临时费项验证数字
      costItemNum: function (v, i) {
        if (v === 0) return;
        if (!Number(v)) {
          this.costItem[i].amountTPay = 0;
          hl.toast('临时费项金额不是数字')
        }
      },
      //编辑临时费项
      editCostItem: function (e) {
        $(e.srcElement).addClass('hide').siblings('button').removeClass('hide');
        $(e.srcElement).parents('.dy-flex').find('input').removeClass('hide')
        $(e.srcElement).parents('.dy-flex').find('b').addClass('hide')
      },
      editIdCostItem: function (id, name, memo, money, item) {
        var _this = this;
        hlhttp.put({
          url: 'bill/expense',
          data: {
            id: id, //费项ID
            expense_name: name,
            expense_amount: money,
            expense_memo: memo || '#',
            expense_name_update_flag: item.expense_name_update_flag == 'Y' ? 'Y' : 'N',
            expense_amount_update_flag: item.expense_amount_update_flag == 'Y' ? 'Y' : 'N',
            expense_memo_update_flag: item.expense_memo_update_flag == 'Y' ? 'Y' : 'N'
          },
          success: function (data) {
            hl.toast('编辑临时费项成功')
            _this.getBillData()
            _this.getlogData()
            $('.js-cancel-btn,.js-confirm-btn,.sh-2').addClass('hide')
            $('.js-amend,.sh-1').removeClass('hide')
          }
        })
      },
      //提交临时费项
      submitCostItem: function (i) {
        var _this = this;
        if (!_this.costItem[i].name) {
          hl.toast('临时费项名称不能为空')
          return
        }
        if (!_this.costItem[i].amountTPay) {
          hl.toast('临时费项金额不能为空')
          return
        }
        hlhttp.post({
          url: 'bill/expense',
          data: {
            bill_id: ACCOUNTID, //账单ID
            expense_name: _this.costItem[i].name,
            expense_amount: _this.costItem[i].amountTPay,
            expense_memo: _this.costItem[i].memo || '#'
          },
          success: function (data) {
            _this.isChangeLSFlag = true
            _this.getBillData()
            _this.getlogData()
            hl.toast('提交临时费项成功')
            _this.costItem = [];
            _this.temporary = 0;
          }
        })
      },
      //获取待分配
      getFPData: function (ix, id, flag) {
        var _this = this;
        this.Fp[ix] = {
          index: ix,
          id: id,
          flag: flag
        }
        _this.fpPut = [];

        hlhttp.get({
          url: 'bill/expenses',
          data: {
            bill_id: ACCOUNTID
          },
          success: function (res) {
            // ************ 营业额本次新增逻辑 start **********
            let amountReceivedRent = 0; //固定租金金额
            let commissioAmount = 0; //营业额金额
            let IsCompareRentAmtFlag = false; //判断是否是取其高
            res.map(item => {
              item.flag = true;
              item.styleFlag = false;
              if (item.expenseType == 'R') {
                amountReceivedRent = item.amountReceived;
              }
              if (item.expenseType == 'CM') {
                commissioAmount = item.amountReceived;
              }
            })
            if (_this.billData.compareRentAmtFlag && _this.billData.commissonConfirmFlag && _this.billData.commissionFlag) {
              if (_this.billData.compareRentAmtFlag == 'Y' && _this.billData.commissionFlag == 'Y' && _this.billData.commissonConfirmFlag == 'Y') {
                IsCompareRentAmtFlag = true;
              }
            }
            if (IsCompareRentAmtFlag) {
              res.map(item => {
                if (item.expenseType == 'CM') {
                  if (item.amountReceived <= amountReceivedRent) {
                    item.flag = false;
                    item.styleFlag = true;
                  }
                }
                if (item.expenseType == 'R') {
                  if (item.amountReceived <= commissioAmount) {
                    item.flag = false;
                    item.styleFlag = true;
                  }
                }
              })
            }
            // ************ 营业额本次新增逻辑 end *************
            _this.fPData = res;
            for (var i = 0; i < _this.fPData.length; i++) {
              _this.fpPut.push({
                a: '',
                b: ''
              })
              _this.jlFp.push({
                e: '',
                l: '',
                id: ''
              })
              _this.fPData[i].flag = false;
            }
            _this.fPIS = _this.billData.transactions[ix].amountTPay;
            _this.NIS = _this.billData.transactions[ix].amountTPay;
            _this.fpFlag = true;
          }
        })
      },
      //批量分配
      allFp: function () {
        var _this = this;
        _this.fpPut = [];
        var arr = [];
        _this.fPIS = 0;
        _this.NIS = 0;
        $('.gathering .list-head').find('.gathering-select').each(function (index, el) {
          if ($(el).hasClass('g-active')) {
            arr.push($(el).parents('.list-head').index() - 1)
          }
        });
        hlhttp.get({
          url: 'bill/expenses',
          data: {
            bill_id: ACCOUNTID
          },
          success: function (res) {
            _this.fPData = res;
            for (var i = 0; i < _this.fPData.length; i++) {
              _this.fpPut.push({
                a: '',
                b: ''
              })
              _this.jlFp.push({
                e: '',
                l: '',
                id: ''
              })
            }
            for (var j = 0; j < arr.length; j++) {
              _this.fPIS += _this.billData.transactions[arr[j]].amountTPay;
              _this.NIS += _this.billData.transactions[arr[j]].amountTPay;
            }
            _this.fpFlag = true;
          }
        })
      },
      //计算分配金额
      computedFP: function (i) {
        this.fPIS = this.NIS;
        var arr = [];
        $('.js-select-checkbox').each(function (index, el) {
          if ($(el).hasClass('active')) {
            arr.push($(el).parent().siblings('.je').text())
          }
        });
        for (var i = 0; i < this.fpPut.length; i++) {
          this.fPIS -= this.fpPut[i].a
          this.fPIS -= this.fpPut[i].b
        }
        for (var i = 0; i < arr.length; i++) {
          this.fPIS -= Number(arr[i])
        }
      },
      //判断分配金额金额
      ifLing: function (n, i, k, m, id) {
        if (n == 0) {
          this.jlFp[i].id = id;
          this.jlFp[i].e = this.fpPut[i].a || '0';
          this.jlFp[i].l = this.fpPut[i].b || '0';
          this.computedFP(i)
          return
        }
        if (n == '') {
          return
        };
        if (n < 0) {
          if (k == 'a') this.fpPut[i].a = '';
          if (k == 'b') this.fpPut[i].b = '';
          hl.toast('金额填写错误')
          return
        }
        if (!Number(n)) {
          if (k == 'a') this.fpPut[i].a = '';
          if (k == 'b') this.fpPut[i].b = '';
          hl.toast('金额填写错误')
          return
        }
        if (n > m) {
          hl.toast('实收不能大于应收')
          if (k == 'a') this.fpPut[i].a = '';
          if (k == 'b') this.fpPut[i].b = '';
          this.computedFP(i)
          return
        }
        if (Number(n) > Number(this.fPIS).toFixed(2)) {
          hl.toast('不能大于可分配金额')
          if (k == 'a') this.fpPut[i].a = '';
          if (k == 'b') this.fpPut[i].b = '';
          this.computedFP(i)
          return
        }
        if (this.fPIS < 0) {
          hl.toast('可分配金额不能小于0')
          if (k == 'a') this.fpPut[i].a = '';
          if (k == 'b') this.fpPut[i].b = '';
          return
        }
        this.computedFP(i)
        this.jlFp[i].id = id;
        this.jlFp[i].e = this.fpPut[i].a || '0';
        this.jlFp[i].l = this.fpPut[i].b || '0';
      },
      //临时费项
      costItemFp: function (v, i, e, id) {
        if (!$(e.srcElement).hasClass('active')) {
          if (v > Number(this.fPIS).toFixed(2)) {
            hl.toast('不能大于可分配金额')
            return
          }
          if (this.fPIS < 0) {
            hl.toast('可分配金额不能小于0')
            return
          }
          $(e.srcElement).addClass('active')
          this.jlFp[i].id = id;
          this.jlFp[i].e = v;
          this.jlFp[i].l = '0';
          this.fPIS -= v;
        } else {
          $(e.srcElement).removeClass('active')
          this.jlFp[i].id = '';
          this.jlFp[i].e = '';
          this.jlFp[i].l = '';
          this.fPIS += v;
        }
      },
      //关闭分配
      closeFP: function () {
        this.fpFlag = false;
        this.closeFlag = false;
        for (var i = 0; i < this.Fp.length; i++) {
          this.Fp[i] = {
            index: '',
            id: '',
            flag: ''
          }
        }
      },
      //显示批量分配按钮
      showPlFp: function (i, id, flag) {
        if (!flag) {
          this.billData.transactions[i].flag = true;
          this.Fp[i] = {
            index: i,
            id: id,
            flag: !flag
          }
          this.plFp++
        } else {
          this.billData.transactions[i].flag = false;
          this.Fp[i] = {
            index: i,
            id: id,
            flag: !flag
          }
          this.plFp--
        }
      },
      //提交分配
      submitFp: function () {
        var _this = this;
        var fpIds = [];
        var fpJson = {
          ids: [],
          a: [],
          l: []
        }
        for (var i = 0; i < this.Fp.length; i++) {
          if (this.Fp[i].flag) {
            fpIds.push(this.Fp[i].id)
          }
        }
        for (var i = 0; i < this.jlFp.length; i++) {
          if (this.jlFp[i].id) {
            fpJson.ids.push(this.jlFp[i].id)
            fpJson.a.push(this.jlFp[i].e)
            fpJson.l.push(this.jlFp[i].l)
          }
        }
        if (Number(this.fPIS).toFixed(2) != 0) return;

        hlhttp.put({
          url: 'bill/transaction/_assign',
          data: {
            bill_id: ACCOUNTID, //账单ID
            expense_ids: fpJson.ids.toString(),
            transaction_ids: fpIds.toString(),
            expenses: fpJson.a.toString(),
            late_fees: fpJson.l.toString()
          },
          success: function () {
            _this.getBillData();
            _this.getlogData();
            _this.fpFlag = false;
          }
        })
      },
      // 催缴
      paymant() {
        hllayer.confirm1('将向客户发送一条付款信息，确定立即发送', () => {
          var that = this
          hlhttp.post({
            url: 'tenant/bills/batch_reminder',
            data: {
              'bill_ids': ACCOUNTID
            },
            success: function (res) {
              if (res.sendFailedNum > 0) {
                that.getResult(res.msgSendOperateGroup)
                return
              }
              hl.toast('发送成功')
            }
          })
        }, () => {
          $('.hllayer-page, .hllayer-mask').remove()
        })
      },
      getResult(code) {
        hlhttp.get({
          url: 'tenant/bills/batch_reminder/fail_cause_list',
          data: {
            'msg_send_operate_group': code
          },
          success: function (res) {
            let data = JSON.parse(res[0].resultDetail)
            hl.toast(data.failure_reasons[0])
          }
        })
      },
      //提交账单
      submitBill: function () {
        if (!this.editFlag) {
          hl.toast('请先保存')
          return
        }
        if (this.billData.commissionFlag && this.billData.commissonConfirmFlag) {
          if (this.billData.commissionFlag == 'Y' && this.billData.commissonConfirmFlag == 'N') {
            this.IsCompareRentAmtFlag = true;
            return
          }
        }
        this.closeFlag = true;
      },
      submitQs: function () {
        var arr = {
            ids: [],
            a: [],
            l: [],
            z: []
          },
          item, _this = this;
        for (var i = 0; i < this.billData.expenses.length; i++) {
          item = this.billData.expenses[i];
          if (item.paymentState !== 'APE') {
            arr.ids.push(item.id)
            arr.a.push(item.amountDerate)
            arr.l.push(item.lateFeeDerate)
            arr.z.push(item.lateFeeReceived)
          }
        }

        let data = {
          bill_id: ACCOUNTID, //账单ID
          expense_ids: '#', // 费项ID列表，逗号分割
          amountDerate: '#', // 减免费用列表，逗号分割，与费项ID对应
          lateFeeDerate: '#', //减免滞纳金列表，逗号分割，与费项ID对应
          late_fees: '#',
          is_submit: 'Y',
        }
        let statusArr = []
        if (this.billBpmConfigArr.length) {
          this.billBpmConfigArr.map(item => {
            if (item.openFlag == 'Y' && item.dictCode == "BPM_JEWBH" && !this.isChangeJMFlag && !this.isChangeLSFlag && this.billData.sourceType != 'C') {
              statusArr.push(item.dictCode)
            }
            if (item.openFlag == 'Y' && item.dictCode == "BPM_JEJM" && this.isChangeJMFlag && this.billData.sourceType != 'C') {
              statusArr.push(item.dictCode)
            }
            if (item.openFlag == 'Y' && item.dictCode == "BPM_JEZJ" && this.isChangeLSFlag && this.billData.sourceType != 'C') {
              statusArr.push(item.dictCode)
            }
            if (item.openFlag == 'Y' && item.dictCode == "BPM_LSZD" && this.billData.sourceType == 'C') {
              statusArr.push(item.dictCode)
            }
          })
        }
        data.bill_bpm_value = statusArr + '' || '#'
        hlhttp.put({
          url: 'bill',
          data: data,
          success: function () {
            hl.toast('账单提交成功')
            _this.getBillData()
            _this.getlogData()
            _this.closeFlag = false;
          }
        })
      },
      //大图浏览
      getBigPic: function (img) {
        var temp = img ? img.split(',') : null;
        $.imageShow(temp)
      },
      //说明a
      getMemo: function (content, flag) {
        this.memo = {
          content: content,
          flag: flag
        }
      },
      // 获取项目模板列表
      getProjectModuleList: function (fn) {
        var self = this;
        hlhttp.get({
          url: 'project/print_template_list',
          data: {
            'project_id': self.proid
          },
          success: function (res) {
            var isUserDefault = false; // 判断是否存在用户默认模版
            res.forEach((el, i) => {
              if (el.type == 'C') isUserDefault = true;
            })
            if (fn) fn(isUserDefault)
          }
        })
      },
      //打印
      print: function () {
        var self = this;
        window.localStorage.setItem('PROJECTID', self.proid)

        var goToPrintTmp = function (isUserDefault) {
          var tenantId = JSON.parse(window.localStorage.getItem('userMes')).tenantId;
          if (isUserDefault == true) hlUrlUtil.goTo('billPrintCommonTmp', {
            'billId': ACCOUNTID,
            'contractId': CONTRACTID,
            'projectId': self.proid,
            ddtab: true
          })
          if (isUserDefault == false) {
            if (tenantId === '15' || tenantId === '17') {
              hlUrlUtil.goTo('YYNoticePrint', {
                'id': ACCOUNTID,
                'aid': CONTRACTID,
                ddtab: true
              })
            } else if (tenantId === '30') {
              hlUrlUtil.goTo('XYPrint', {
                'id': ACCOUNTID,
                'aid': CONTRACTID,
                ddtab: true
              })
            } else if (tenantId === '2' || tenantId === '5') {
              hlUrlUtil.goTo('JYPrint', {
                'id': ACCOUNTID,
                'aid': CONTRACTID,
                ddtab: true
              })
            } else {
              hlUrlUtil.goTo('billPrintCommonTmp', {
                'billId': ACCOUNTID,
                'contractId': CONTRACTID,
                'projectId': self.proid,
                ddtab: true
              })
            }

          }
        }

        self.getProjectModuleList(goToPrintTmp);
      },
      print1: function () {
        var ids = window.localStorage.getItem('userMes')
        window.location.href = window.location.protocol+'//' + window.location.host + window.location.pathname + '#/YYRemindPrint?id=' + ACCOUNTID + '&aid=' + CONTRACTID
        window.localStorage.setItem('PROJECTID', this.proid)
      },
      editCountMes: function () {
        this.isEditCountMes = true
      },
      saveCountMes: function () {
        hlhttp.put({
          url: 'bill/payment_deadline',
          data: {
            bill_id: ACCOUNTID,
            payment_deadline: this.receiptDeadlineDate
          },
          success: () => {
            hl.toast('修改成功')
            this.isEditCountMes = false
            this.getBillData()
            this.getlogData()

          }
        })
      },
      receiptDeadlineDateChange: function () {}

    },
    mounted: function () {
      this.getContractUnitsData()
      this.getBillData()
      this.getlogData()
      this.bill_bpm_config()
    }
  })
}())